/**
 * 性能优化工具类
 * 用于提升应用整体性能和用户体验
 */

// 🔥 页面加载优化配置
export const PERFORMANCE_CONFIG = {
  // 页面加载延迟配置
  PAGE_LOAD_DELAY: 50,        // 页面基础内容加载延迟（毫秒）
  CHART_LOAD_DELAY: 100,      // 图表加载延迟（毫秒）
  COMPONENT_LOAD_DELAY: 80,   // 组件懒加载延迟（毫秒）
  
  // 请求优化配置
  REQUEST_TIMEOUT: 10000,     // 请求超时时间（毫秒）
  RETRY_COUNT: 2,             // 请求重试次数
  
  // 缓存配置
  CACHE_DURATION: 5 * 60 * 1000, // 缓存持续时间（5分钟）
}

/**
 * 页面渲染优化 - 分步骤加载页面内容
 * @param callbacks 加载步骤回调函数数组
 */
export const optimizedPageLoad = (callbacks: Array<() => void>) => {
  callbacks.forEach((callback, index) => {
    setTimeout(() => {
      callback()
    }, index * PERFORMANCE_CONFIG.PAGE_LOAD_DELAY)
  })
}

/**
 * 组件懒加载优化
 * @param loadFn 加载函数
 * @param delay 延迟时间（毫秒）
 */
export const lazyLoad = (loadFn: () => void, delay: number = PERFORMANCE_CONFIG.COMPONENT_LOAD_DELAY) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      loadFn()
      resolve(true)
    }, delay)
  })
}

/**
 * 请求优化 - 带重试和缓存的请求
 * @param requestFn 请求函数
 * @param cacheKey 缓存键
 * @param useCache 是否使用缓存
 */
const requestCache = new Map<string, { data: any; timestamp: number }>()

export const optimizedRequest = async <T>(
  requestFn: () => Promise<T>,
  cacheKey?: string,
  useCache: boolean = true
): Promise<T> => {
  // 检查缓存
  if (useCache && cacheKey) {
    const cached = requestCache.get(cacheKey)
    if (cached && Date.now() - cached.timestamp < PERFORMANCE_CONFIG.CACHE_DURATION) {
      return cached.data
    }
  }

  // 执行请求，带重试机制
  let lastError: any
  for (let i = 0; i <= PERFORMANCE_CONFIG.RETRY_COUNT; i++) {
    try {
      const result = await Promise.race([
        requestFn(),
        new Promise<never>((_, reject) => 
          setTimeout(() => reject(new Error('Request timeout')), PERFORMANCE_CONFIG.REQUEST_TIMEOUT)
        )
      ])

      // 缓存结果
      if (useCache && cacheKey) {
        requestCache.set(cacheKey, {
          data: result,
          timestamp: Date.now()
        })
      }

      return result
    } catch (error) {
      lastError = error
      if (i < PERFORMANCE_CONFIG.RETRY_COUNT) {
        // 等待后重试
        await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)))
      }
    }
  }

  throw lastError
}

/**
 * 并行请求优化
 * @param requests 请求数组
 */
export const parallelRequests = async <T>(requests: Array<() => Promise<T>>): Promise<T[]> => {
  return Promise.all(requests.map(request => request()))
}

/**
 * 清除请求缓存
 * @param cacheKey 可选的特定缓存键，不传则清除所有缓存
 */
export const clearRequestCache = (cacheKey?: string) => {
  if (cacheKey) {
    requestCache.delete(cacheKey)
  } else {
    requestCache.clear()
  }
}

/**
 * 获取缓存统计信息
 */
export const getCacheStats = () => {
  return {
    size: requestCache.size,
    keys: Array.from(requestCache.keys())
  }
}

/**
 * 防抖函数 - 优化频繁操作
 * @param fn 要防抖的函数
 * @param delay 延迟时间
 */
export const debounce = <T extends (...args: any[]) => any>(
  fn: T,
  delay: number = 300
): T => {
  let timeoutId: number
  return ((...args: any[]) => {
    clearTimeout(timeoutId)
    timeoutId = window.setTimeout(() => fn(...args), delay)
  }) as T
}

/**
 * 节流函数 - 优化高频事件
 * @param fn 要节流的函数
 * @param delay 间隔时间
 */
export const throttle = <T extends (...args: any[]) => any>(
  fn: T,
  delay: number = 300
): T => {
  let lastCall = 0
  return ((...args: any[]) => {
    const now = Date.now()
    if (now - lastCall >= delay) {
      lastCall = now
      return fn(...args)
    }
  }) as T
} 